<template>
  <a-card class="bookmark-list">
    <template #extra>
      <div class="header-actions">
        <a-button @click="exportBookmarks">
          <template #icon><export-outlined /></template>
          导出
        </a-button>
        <a-upload accept=".json" :show-upload-list="false" :before-upload="importBookmarks">
          <a-button>
            <template #icon><import-outlined /></template>
            导入
          </a-button>
        </a-upload>
        <a-button type="primary" @click="$emit('add')">
          <template #icon>
            <plus-outlined />
          </template>
          新建书签
        </a-button>
      </div>
    </template>
    <div v-if="bookmarks.length === 0" style="text-align: center; padding: 40px; color: #999">暂无书签数据</div>
    <draggable
      v-else
      v-model="sortableBookmarks"
      :animation="200"
      item-key="id"
      handle=".bookmark-drag-handle"
      tag="div"
      class="bookmark-grid"
      ghost-class="ghost"
      chosen-class="chosen"
      drag-class="drag"
      :delay="50"
      :delayOnTouchOnly="true"
      :scroll="true"
      :scrollSensitivity="60"
      :scrollSpeed="20"
      @start="onDragStart"
      @end="onDragEnd"
    >
      <template #item="{ element: bookmark }">
        <BookmarkItem :bookmark="bookmark" @edit="$emit('edit', bookmark)" @delete="$emit('delete', bookmark)" />
      </template>
    </draggable>
  </a-card>
</template>

<script setup>
import { PlusOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons-vue'
import draggable from 'vuedraggable'
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useBookmarkStore } from '@/stores/bookmark'
import BookmarkItem from './BookmarkItem.vue'

const props = defineProps({
  bookmarks: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['add', 'edit', 'delete', 'sort'])

const store = useBookmarkStore()
const loading = ref(false)

const sortableBookmarks = computed({
  get: () => props.bookmarks,
  set: (value) => {
    emit('sort', value)
  }
})

const onDragStart = () => {
  loading.value = true
}

const onDragEnd = () => {
  loading.value = false
}

// 导出书签功能
const exportBookmarks = () => {
  const data = {
    categories: store.categories.filter((c) => c.key !== 'all'), // 排除"全部"分类
    bookmarks: store.bookmarks
  }
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `bookmarks-${new Date().toISOString().split('T')[0]}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  message.success('导出成功')
}

// 导入书签功能
const importBookmarks = (file) => {
  const reader = new FileReader()
  reader.onload = async (e) => {
    try {
      const data = JSON.parse(e.target.result)
      if (data.categories && data.bookmarks) {
        await store.importData(data)
        message.success('导入成功')
      } else {
        message.error('文件格式不正确')
      }
    } catch (error) {
      message.error('导入失败，请检查文件格式')
    }
  }
  reader.readAsText(file)
  return false // 阻止自动上传
}
</script>

<style scoped>
.bookmark-list {
  height: 100%;
  overflow: hidden;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ant-card-extra) {
  padding: 0;
}

:deep(.ant-btn) {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  height: 32px;
  padding: 4px 12px;
}

:deep(.anticon) {
  font-size: 14px;
}

:deep(.ant-card-body) {
  height: calc(100% - 57px);
  overflow-y: auto;
  padding: 16px !important;
}

.bookmark-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
  padding: 8px;
  width: 100%;
}

.ghost {
  opacity: 0.3;
  background: #f0f7ff;
  border: 1px dashed #344767;
  box-shadow: none !important;
  transform: scale(0.98);
}

.chosen {
  background: #fff;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  transform: scale(1.02);
  z-index: 10;
  border-color: #344767;
}

.drag {
  opacity: 1;
  background: #f0f7ff;
  border: 1px solid #1890ff;
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.15);
  transform: scale(1.02);
  z-index: 20;
}
</style>
